package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.commom.exception.CustException;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.feigns.AdminFeign;
import com.heima.model.admin.pojo.AdChannel;
import com.heima.model.article.pojo.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.AggBehaviorDTO;
import com.heima.utils.common.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author by jojo
 * @Date 2022/3/13
 * @Description
 */
@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AdminFeign adminFeign;
    @Autowired
    private ApArticleMapper articleMapper;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
      //1 查询前5天的 （已上架、未删除） 文章数据
        //获取前五天的时间段
        String beginDate = LocalDateTime.now().minusDays(5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        List<ApArticle> apArticleList = articleMapper.selectArticleByDate(beginDate);
        if (CollectionUtils.isEmpty(apArticleList)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"最近5天没有上架的文章！！！");
        }
        //2 计算热点文章分值
        List<HotArticleVo> hotArticleVoList= computeArticleScore(apArticleList);
        if (CollectionUtils.isEmpty(hotArticleVoList)) {
            log.info("最近5天没有文章上架！！！");
            return;
        }
        //3 为每一个频道缓存热点较高的30条文章
        cacheTagToRedis(hotArticleVoList);
    }

    /**
     * 重新计算文章热度  更新redis缓存
     * @param aggBehavior
     */
    @Override
    public void updateApArticle(AggBehaviorDTO aggBehavior) {
        //1.根据文章id判断文章数据是否为空
        ApArticle apArticle = articleMapper.selectById(aggBehavior.getArticleId());
        if (apArticle==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该文章不存在");
        }
        //2.根据聚合之后的数据，更改当前文章的行为分数值
        int views= (int)(apArticle.getViews()==null?0:apArticle.getViews()+aggBehavior.getView());
        apArticle.setViews(views);
        int likes= (int)(apArticle.getLikes()==null?0:apArticle.getLikes()+aggBehavior.getLike());
        apArticle.setLikes(likes);
        int comment= (int)(apArticle.getComment()==null?0:apArticle.getComment()+aggBehavior.getComment());
        apArticle.setComment(comment);
        int collect= (int)(apArticle.getCollection()==null?0:apArticle.getCollection()+aggBehavior.getCollect());
        apArticle.setCollection(collect);
        //执行修改语句
        articleMapper.updateById(apArticle);
        //3.重新计算文章热度得分
        Integer score = computeScore(apArticle);
        // 4. 判断文章发布时间  是否是今天  如果是  热度乘3
        String nowDateStr = DateUtils.dateToString(new Date());
        String publishDateStr = DateUtils.dateToString(apArticle.getPublishTime());
        if (nowDateStr.equals(publishDateStr)) {
            score=score*3;
        }
        // 5.  基于当前文章 替换当前频道热度较低的文章
        updateArticleCache(score,apArticle,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+apArticle.getChannelId());
        //基于当前文章 替换推荐频道热度较低的文章
        updateArticleCache(score,apArticle,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
    }

    private void updateArticleCache(Integer score, ApArticle apArticle, String cacheKey) {
        // 1. 从redis中查询对应的热点文章
        String hotArticleJson  = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isBlank(hotArticleJson)) {
            return;
        }
        // 2. 判断当前文章是否在热点文章中存在
        List<HotArticleVo> hotArticleVoList = JSON.parseArray(hotArticleJson, HotArticleVo.class);
        boolean flag=false;
        //存在，替换热度得分
        for (HotArticleVo articleVo : hotArticleVoList) {
            if (articleVo.getId().equals(apArticle.getId())) {
                articleVo.setScore(score);
                flag=true;
                break;
            }
        }
        // 3. 如果不存在，将当前文章封装成HotArticleVo 保存到热点文章列表中
        if (!flag) {
            hotArticleVoList.add(parseArticleVo(apArticle));
        }
        // 4. 重新将热点文章排序  并 截取 前30条文章
        hotArticleVoList= hotArticleVoList.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        // 5.  更新缓存
        redisTemplate.opsForValue().set(cacheKey,JSON.toJSONString(hotArticleVoList));
    }

    private HotArticleVo parseArticleVo(ApArticle apArticle) {
        HotArticleVo articleVo = new HotArticleVo();
        BeanUtils.copyProperties(apArticle,articleVo);
        //计算热度得分
        Integer score = computeScore(apArticle);
        articleVo.setScore(score);
        return articleVo;
    }


    /**
     * 频道缓存热点较高的30条文章
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        //1 远程查询所有的频道列表
        ResponseResult<List<AdChannel>> listResponseResult = adminFeign.selectChannels();
        if (!listResponseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用频道列表出错！！！");
        }

        List<AdChannel> channelList = listResponseResult.getData();
        if (CollectionUtils.isEmpty(channelList)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"频道列表空空如也！！！");
        }
        //2 遍历频道列表，筛选当前频道下的文章
        for (AdChannel adChannel : channelList) {
            //3 给每个频道下的文章进行缓存
            List<HotArticleVo> hotArticleByTag = hotArticleVoList.stream()
                    //当前频道的文章列表
                    .filter(hotArticleVo -> hotArticleVo.getChannelId().equals(adChannel.getId()))
                    .collect(Collectors.toList());
            //缓存热点文章到Redis
            sortAndCache(hotArticleByTag,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+adChannel.getId());
        }
        //4 给推荐频道缓存30条数据  所有文章排序之后的前30条
        sortAndCache(hotArticleVoList,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);

    }

    private void sortAndCache(List<HotArticleVo> hotArticleVoList, String cacheKey) {
        hotArticleVoList = hotArticleVoList.stream()
                //按照得分降序排序，默认是升序  --》reversed改为降序
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        //热点文章存入Redis
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVoList));
    }

    /**
     * 计算热点文章分值
     * @param apArticleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> apArticleList) {
        return apArticleList.stream()
                .map(apArticle -> {
                    HotArticleVo articleVo = new HotArticleVo();
                    //将文章内容拷贝到vo中
                    BeanUtils.copyProperties(apArticle,articleVo);
                    //计算文章分值算法
                    Integer score=computeScore(apArticle);
                    articleVo.setScore(score);
                    return articleVo;
                })
                .collect(Collectors.toList());
    }

    /**
     * 计算文章分值算法
     * @param apArticle 文章对象
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        int score=0;
        //阅读
        if (apArticle.getViews()!=null){
            score+=apArticle.getViews()* ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        //点赞
        if (apArticle.getLikes()!=null){
            score+=apArticle.getLikes()* ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        //评论
        if (apArticle.getComment()!=null){
            score+=apArticle.getComment()* ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        //收藏
        if (apArticle.getCollection()!=null){
            score+=apArticle.getCollection()* ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
